package com.breaktian.assemble.router.parse;


import com.breaktian.assemble.utils.LogUtil;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.util.ArrayList;

/**
 * Created by keke.tian on 2017/7/31.
 */

public class SaxHandler extends DefaultHandler {

    private Rule rule;
    private String content;
    private RouterXml routerXml;
    private ArrayList<Rule> ruleList;
    private ArrayList<String> schemaPrefixList;


    public SaxHandler(){
    }

    public RouterXml getRouterXml(){
        return routerXml;
    }

    @Override
    public void startDocument() throws SAXException {
        super.startDocument();
        LogUtil.d("startDocument");
        routerXml = new RouterXml();
        ruleList = new ArrayList<Rule>();
        schemaPrefixList = new ArrayList<String>();
        routerXml.setRuleList(ruleList);
        routerXml.setSchemaPrefixList(schemaPrefixList);
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        super.startElement(uri, localName, qName, attributes);

        LogUtil.d("startElement uri:"+uri+",localName:"+localName+",qName:"+qName);

        if("rule".equals(qName)){
            rule = new Rule();
        }else if("schema-prefix".equals(qName)){

        }


    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        super.characters(ch, start, length);
        content = new String(ch, start, length);
        LogUtil.d("characters:"+content);
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        super.endElement(uri, localName, qName);
        LogUtil.d("endElement uri:"+uri+",localName:"+localName+",qName:"+qName);
        if("rule".equals(qName)){
            ruleList.add(rule);
        }

        if("prefix".equals(qName)){
            schemaPrefixList.add(content);
        }else if("default-webview".equals(qName)){
            routerXml.setDefaultWebviewSchema(content);
        }else if("schema".equals(qName)){
            rule.setSchema(content);
        }else if("action".equals(qName)){
            rule.setAction(content);
        }else if("class".equals(qName)){
            rule.setClazz(content);
        }

    }

    @Override
    public void endDocument() throws SAXException {
        super.endDocument();
        LogUtil.d("endDocument");

    }
}
